package com.rrd.hive.udf;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.hive.ql.metadata.HiveException;

import java.util.*;

@Description(
        name = "json_to_map",
        value = "_FUNC_(text) - Creates a map by json string ",
        extended = "parse json string to map"
)
public class JsonToMapUDF extends UDF {

    public Map<String, String> evaluate(String str) throws HiveException {
        Map<String, String> valueMap = new HashMap();
        if (!str.equals("") && !str.equals("null")) {
            try{
                JSONObject jsonObj = JSONObject.parseObject(str);
                for (String key : jsonObj.keySet()) {
                    String val = jsonObj.getString(key);
                    valueMap.put(key, val);
                }
            } catch (JSONException e) {
                System.out.println("json parse error:" + str);
            }
        }
        return valueMap;
    }
}
